<?php
class CF_Session_SaveHandler_Db
	extends CF_Db_Table_Abstract
	implements CF_Session_SaveHandler_Interface
{
	/**
	 * 
	 * @var string
	 */
	protected $_name = 'session';
	
	/**
	 * 
	 * @var string
	 */
	protected $_path;
	
	/**
	 * 
	 * @var string
	 */
	protected $_sessionName;
	
	/**
	 * 
	 * @var int
	 */
	protected $_lifetime = 10000;
	
	/**
	 * @var $_columns array
	 */
	protected $_columns = array(
		'id'		=> 'id',
		'modified'	=> 'modified',
		'lifetime'	=> 'lifetime',
		'data'		=> 'data'
	);
	
	public function __construct($table = null, array $columns = null)
	{
		$this->setTableName($table);
		if(null !== $columns) $this->setColumnDefinition($columns);
	}
	
	/**
	 * 
	 * @param array $column
	 * @return CF_Session_SaveHandler_Db
	 */
	public function setColumnDefinition(array $columns)
	{
		$this->_columns = $columns;
		return $this;
	}
	
	/**
	 * 
	 * @param string $path
	 * @param string $name
	 * @return boolean
	 */
	public function open($path, $name){
		$this->_path = $path;
		$this->_sessionName = $name;
		return true;
	}
	
	/**
	 * @return boolean
	 */
	public function close(){
		return true;
	}
	
	/**
	 * 
	 * @param string $id
	 * @return mixed
	 */
	public function read($id){
		return $this->getCell($id, $this->_columns['data']);
	}
	
	/**
	 * 
	 * @param string $id
	 * @param string $data
	 * @return boolean
	 */
	public function write($id, $data){
		$rec = array(
			$this->_columns['modified'] => time(),
			$this->_columns['lifetime']	=> $this->_lifetime,
			$this->_columns['data']	=> $data
		);
		
		# if has data, update modify time & data
		if($this->has($id))
			return false !== $this->updateById($id, $rec);
		
		$rec[$this->_columns['id']] = $id;
		
		# insert if not exist
		return (boolean) $this->insert($rec);
	}
	
	/**
	 * 
	 * @param string $id
	 * @return boolean
	 */
	public function destroy($id){
		return false !== $this->deleteById($id);
	}
	
	/**
	 * 
	 * @param int $maxlifetime
	 * @return boolean
	 */
	public function gc($maxlifetime){
		$where = new CF_Db_Expr($this->_columns['modified'] . '+' . $this->_columns['lifetime'] . '< %s', time());
		//return fasle !== $this->delete();
	}
}